package com.创建型模式.工厂模式.工厂方法模式;

import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;

/**
 * 产品接
 */
interface Product{
    public void show();
}

/**
 * 产品一
 */
class ProductOne implements  Product{
    @Override
    public void show() {
        System.out.println("我是产品一号");
    }
}

/**
 * 二号产品
 */
class ProductTwo implements  Product{
    @Override
    public void show() {
        System.out.println("我是二号产品");
    }
}

/**
 * 工厂生产接口
 */
interface Factory{
    public Product newProduct();
}

/**
 * 一号工厂
 */
class FactoryOne implements Factory{
    @Override
    public Product newProduct() {
        System.out.println("一号生产线");
        return new ProductOne();
    }
}

/**
 * 二号生产工厂
 */
class FactoryTwo implements Factory{
    @Override
    public Product newProduct() {
        System.out.println("二号生产线");
        return new ProductTwo();
    }
}

/**
 * 读取配置文件类
 */
class ReadXML{
    public static Object getObject(){

        try {
          //创建文档对象
            DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = df.newDocumentBuilder();
            Document doc ;
            doc = (Document) builder.parse(new File("src/img/factory.xml"));
            //获取包含类名的文本节点
            NodeList nl = doc.getElementsByTagName("className");
            Node classNode = nl.item(0).getFirstChild();
            //包名
            String cName = "com.创建型模式.工厂模式.工厂方法模式."+classNode.getNodeValue();
            //获取classs对象
            Class<?> c = Class.forName(cName);
            //实例化对象
            Object obj = c.newInstance();
            return  obj;
        } catch (Exception e) {
            e.printStackTrace();
            return  null;
        }

    }
}
/**
 * 工厂实现
 */
public class SimpleFactory {
    public static void main(String[] args) {
      Product one = new FactoryOne().newProduct();
      one.show();
      Product two = new FactoryTwo().newProduct();
      two.show();
      ////////读取配置文件/////////////
        try {
            Product a;
            Factory f;
            f = (Factory) ReadXML.getObject();
            a = f.newProduct();
            a.show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
